package org.school.streaming.net.client.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramSocket;

import org.school.streaming.net.RequestType;
import org.school.streaming.net.State;
import org.school.streaming.net.client.Client;

/**
 * @authors Jeffrey Goudzwaard,
 * 			Davin Terrizzi
 * @version	1.0
 * @date	18-4-2013
 */

/**
 * Class representing ActionListener behind SETUP button in Client GUI
 * @author Davin
 *
 */
public class btnSetupListener implements ActionListener
{
	@Override
	public void actionPerformed( ActionEvent ae )
	{
		System.out.println( "Setup Button pressed!" );
		
		// Get Client instance
		Client client = Client.getClient();
		
		
		// Check Client state and send right request accordingly
		// Initialize UDP-socket if connected succesfully and set new state
		if( client.getState() == State.INIT )
		{
			try
			{
				client.setDatagramSocket( new DatagramSocket( client.getPort() ) );
				client.getDatagramSocket().setSoTimeout( 5 );
			}
			catch( IOException e )
			{
				System.err.println( e );
				System.err.println( Thread.currentThread().getStackTrace()[1] );
			}
			
			client.setSeqnr( 1 );
			
			client.sendRequest( RequestType.SETUP );
			
			if( client.parseServerResponse() != 200 )
			{
				System.err.println( "Error 100: Invalid Server Response!" );
			}
			else
			{
				client.setState( State.READY );
				System.out.println( "New RTSP state: READY" );
			}
		}
	}
}
